Swadhin Biswas feat(api): add runner, analytics, packages, and security services · 3/6/2026
28f7954
54 lines · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { getDatabase, schema } from "@/db";
import { sshKeys } from "@/db/schema";
import { notFound, success, unauthorized } from "@/lib/api";
import { getUserFromRequest } from "@/lib/auth";
import type { APIRoute } from "astro";
import { and, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";

import { withErrorHandler } from "@/lib/errors";
import { logger } from "@/lib/logger";

export const DELETE: APIRoute = withErrorHandler(
  async ({ request, params }) => {
    const tokenPayload = await getUserFromRequest(request);
    if (!tokenPayload) {
      return unauthorized();
    }

    const { id } = params;
    if (!id) {
      return notFound("Key ID is required");
    }

    const db = getDatabase() as NodePgDatabase<typeof schema>;

    // Delete key ensuring it belongs to the user
    const result = await db
      .delete(sshKeys)
      .where(and(eq(sshKeys.id, id), eq(sshKeys.userId, tokenPayload.userId)))
      .returning();

    if (result.length === 0) {
      return notFound("SSH key not found or not authorized");
    }

    // Audit log
    const { logAudit, getRequestMeta } = await import("@/lib/audit");
    const { ip, userAgent } = getRequestMeta(request);
    await logAudit({
      userId: tokenPayload.userId,
      action: "ssh_key.delete",
      actorIp: ip,
      actorUserAgent: userAgent,
      targetType: "ssh_key",
      targetId: id,
      targetName: result[0]?.title ?? null,
    });

    logger.info({ userId: tokenPayload.userId, keyId: id }, "SSH key deleted");

    return success({ message: "SSH key deleted successfully" });
  },
);